
package com.example.administrator.android2019.ch3Activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.style.TtsSpan;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.android2019.R;

public class SPAActivity extends AppCompatActivity {
       Button btn_read,btn_write;
       TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spa);
        btn_read=findViewById(R.id.ch3_file_sp_btn_read);
        btn_write=findViewById(R.id.ch3_file_sp_btn_write);
        textView=findViewById(R.id.ch3_file_sp_tv);

        View.OnClickListener listener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                switch (v.getId()){
                    case  R.id.ch3_file_sp_btn_write:
                        write();
                        break;
                    case R.id.ch3_file_sp_btn_read:
                     read();
                     break;
                }
            }
        };
        btn_read.setOnClickListener(listener);
        btn_write.setOnClickListener(listener);
    }

    private void write() {
        SharedPreferences sp=this.getSharedPreferences("hxy",MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString("name","zhangsan");
        editor.putInt("age",20);
        editor.commit();
        Toast.makeText(this,"写入成功",Toast.LENGTH_SHORT).show();

    }

    private void read() {
        SharedPreferences sp=this.getSharedPreferences("hxy",MODE_PRIVATE);
        String name=sp.getString("name",null);
        int age =sp.getInt("age",0);
        textView.setText(name+"  "+age);
    }
}
